import * as turf from "@turf/turf";

export function toPointGeojson(points, properties) {
	const features = points.map((point) => turf.point(point, properties));
	const data = turf.featureCollection(features);
	return data;
}

export function toEnvelopedGeojson(points, properties) {
	const features = points.map((point) => turf.point(point, properties));
	const collection = turf.featureCollection(features);
	const enveloped = turf.envelope(collection);

	return enveloped;
}

export function toCentroidGeojson(points) {
	const features = points.map((point) => turf.point(point));
	const collection = turf.featureCollection(features);
	const center = turf.centroid(collection);

	return center;
}

export function getEditIndex(points, latLng, radius) {
	// const editIndex = points.findIndex((point) => {
	//   const source = turf.point(point);
	//   const buffered = turf.buffer(source, radius, { units: "degrees" });
	//   const target = turf.point([latLng.lng, latLng.lat]);

	//   const isWithin = turf.booleanPointInPolygon(target, buffered, {
	//     ignoreBoundary: false,
	//   });

	//   return isWithin;
	// });

	const editIndex = points.findIndex(
		(point) =>
			Math.abs(point[0] - latLng.lng) < radius &&
			Math.abs(point[1] === latLng.lat) < radius,
	);

	return editIndex;
}
